<?php

include 'config.php';

/**
 * Do redirect to a url
 * @param $url
 */
function doRedirect($url) {
    header( "Location: $url" ) ;
}

function doLogout() {
    session_destroy();
}

/**
 * Check if current user is login
 * @return bool
 */
function isLogin() {
    return getCurrentUser() != null;
}

/**
 * Do login by username and password
 * @param $username
 * @param $password
 * @return bool
 */
function doLogin($username, $password) {
    $rs = soap_testValidUser($username, $password);
    if($rs->pIsValid) {
        saveUser($username, $rs->pLanguage, $password);
        return true;
    }
    else
        return false;
}

/**
 * Save user information to session
 * @param $username
 * @param $language
 * @param $password
 */
function saveUser($username, $language, $password) {
    $_SESSION['user'] = array(
        'username' => $username,
        'language' => $language,
        'password' => $password
    );
}

/**
 * Get current login user
 * @return mixed
 */
function getCurrentUser() {
    if(empty($_SESSION['user']))
        return null;
    return $_SESSION['user'];
}

/**
 * Get current language
 * @return string
 */
function getCurrentLanguage() {
    $lang = array(
        1 => 'en',
        2 => 'fr'
    );
    $user = getCurrentUser();
    if(!$user)
        return DEFAULT_LANGUAGE;
    if(!isset($lang[$user['language']]))
        return DEFAULT_LANGUAGE;
    return $lang[$user['language']];
}

/**
 * Change current language
 * @param $lang
 */
function changeLanguage($lang) {
    $langarr = array(
        'en' => 1,
        'fr' => 2
    );
    if(isset($langarr[$lang]) && isLogin()) {
        $_SESSION['user']['language'] = $langarr[$lang];
    }
}

/**
 * Wrapper to call SOAP service
 * @param $username
 * @param $password
 * @return mixed
 */
function soap_testValidUser($username, $password) {
    $client = soap_getSoapClient();
    $param = array(
        'pUser' => $username,
        'pPassword' => $password,
    );

    return $client->isValidUser($param);
}

/**
 * Get center list data
 * @return null|object
 */
function soap_getCenterList()
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language']
					  );
	   return $client->getCenterList($parameters); 
	}
}

/**
 * Gets the list of all thirds
 * @return null|object
 */
function soap_getThirdList($center)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center,
					  'pThirdType' => 16,
					  'pSearchTag' => ''
					  );
	   return $client->getThirdList($parameters); 
	}
}

/**
 * Gets the list of all clients.
 * @return null|object
 */
function soap_getClientList($center,$isActive,$searchTag)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$isActive = $isActive === 'true' ? true : false;
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center,
					  'pSearchTag' => $searchTag,
					  'pIsActive' => $isActive
					  );
	   return $client->getClientList($parameters); 
	}
}

/**
 * Gets the list of all portfolio.
 * @return null|object
 */
function soap_getPortfolioList($center,$searchTag,$isActive)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center,
					  'pSearchTag' => $searchTag,
					  'pIsActive' => TRUE
					  );
	   return $client->getPortfolioList($parameters); 
	}
}

/**
 * Gets the list of all employees.
 * @return null|object
 */
function soap_getEmployeeList()
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language']
					  );
	   return $client->getEmployeeList($parameters); 
	}
}

/**
 * Gets the list of all pools of clients.
 * @return null|object
 */
function soap_getPoolList($center)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center
					  );
	   return $client->getPoolList($parameters); 
	}
}

/**
 * Gets the list of all securities.
 * @return null|object
 */
function soap_getSecurityList($center)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language']
					  );
	   return $client->getSecurityList($parameters); 
	}
}

/**
 * Gets the list of positions by portoflio.
 * @return null|object
 */
function soap_getPositionByPortfolio($center,$deposit,$manager,$client1,$pool,$security,$portfolio,$position,$status,$historical,$valuedate,$nilsecurity,$nilfidu,$nilcash)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$historical = $historical === 'true' ? true : false;
		$nilsecurity = $nilsecurity === 'true' ? true : false;
		$nilcash = $nilcash === 'true' ? true : false;
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center,
					  'pDeposit' => $deposit,
					  'pManager' => $manager,
					  'pClient' => $client1,
					  'pPool' => $pool,
					  'pSecurity' => $security,
					  'pPortfolio' => $portfolio,
					  'pPosition' => $position,
					  'pStatus' => $status,
					  'pHistorical' => $historical,
					  'pValueDate' => $valuedate,
					  'pNilSecurity' => $nilsecurity,
					  'pNilFidu' => FALSE,
					  'pNilCash' => $nilcash,
					  );
	   return $client->getPositionByPortfolio($parameters); 
	}
}

/**
 * Gets the list of positions by client.
 * @return null|object
 */
function soap_getPositionByClient($center,$deposit,$manager,$client1,$pool,$security,$portfolio,$position,$status,$historical,$valuedate,$nilsecurity,$nilfidu,$nilcash)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$historical = $historical === 'true' ? true : false;
		$nilsecurity = $nilsecurity === 'true' ? true : false;
		$nilcash = $nilcash === 'true' ? true : false;
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center,
					  'pDeposit' => $deposit,
					  'pManager' => $manager,
					  'pClient' => $client1,
					  'pPool' => $pool,
					  'pSecurity' => $security,
					  'pPortfolio' => $portfolio,
					  'pPosition' => $position,
					  'pStatus' => $status,
					  'pHistorical' => $historical,
					  'pValueDate' => $valuedate,
					  'pNilSecurity' => $nilsecurity,
					  'pNilFidu' => FALSE,
					  'pNilCash' => $nilcash,
					  );
	   return $client->getPositionByClient($parameters); 
	}
}

/**
 * Gets the list of positions by depositary.
 * @return null|object
 */
function soap_getPositionByDepositary($center,$deposit,$manager,$client1,$pool,$security,$portfolio,$position,$status,$historical,$valuedate,$nilsecurity,$nilfidu,$nilcash)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$historical = $historical === 'true' ? true : false;
		$nilsecurity = $nilsecurity === 'true' ? true : false;
		$nilcash = $nilcash === 'true' ? true : false;
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center,
					  'pDeposit' => $deposit,
					  'pManager' => $manager,
					  'pClient' => $client1,
					  'pPool' => $pool,
					  'pSecurity' => $security,
					  'pPortfolio' => $portfolio,
					  'pPosition' => $position,
					  'pStatus' => $status,
					  'pHistorical' => $historical,
					  'pValueDate' => $valuedate,
					  'pNilSecurity' => $nilsecurity,
					  'pNilFidu' => FALSE,
					  'pNilCash' => $nilcash,
					  );
	   return $client->getPositionByDepositary($parameters); 
	}
}

/**
 * Gets the list of positions by manager.
 * @return null|object
 */
function soap_getPositionBymanager($center,$deposit,$manager,$client1,$pool,$security,$portfolio,$position,$status,$historical,$valuedate,$nilsecurity,$nilfidu,$nilcash)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$historical = $historical === 'true' ? true : false;
		$nilsecurity = $nilsecurity === 'true' ? true : false;
		$nilcash = $nilcash === 'true' ? true : false;
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center,
					  'pDeposit' => $deposit,
					  'pManager' => $manager,
					  'pClient' => $client1,
					  'pPool' => $pool,
					  'pSecurity' => $security,
					  'pPortfolio' => $portfolio,
					  'pPosition' => $position,
					  'pStatus' => $status,
					  'pHistorical' => $historical,
					  'pValueDate' => $valuedate,
					  'pNilSecurity' => $nilsecurity,
					  'pNilFidu' => FALSE,
					  'pNilCash' => $nilcash,
					  );
	   return $client->getPositionBymanager($parameters); 
	}
}

/**
 * Gets the list of all positions.
 * @return null|object
 */
function soap_getAllPosition($center,$deposit,$manager,$client1,$pool,$security,$portfolio,$position,$status,$historical,$valuedate,$nilsecurity,$nilfidu,$nilcash)
{
	$user = getCurrentUser();
    if(!$user)
        return null;

	$client = soap_getSoapClient();
	if($client)
	{
		$historical = $historical === 'true' ? true : false;
		$nilsecurity = $nilsecurity === 'true' ? true : false;
		$nilcash = $nilcash === 'true' ? true : false;
		$parameters = array(
					  'pUser' => $user['username'],
					  'pPassword' => $user['password'],
					  'pLanguage' => $user['language'],
					  'pCenter' => $center,
					  'pDeposit' => $deposit,
					  'pManager' => $manager,
					  'pClient' => $client1,
					  'pPool' => $pool,
					  'pSecurity' => $security,
					  'pPortfolio' => $portfolio,
					  'pPosition' => $position,
					  'pStatus' => $status,
					  'pHistorical' => $historical,
					  'pValueDate' => $valuedate,
					  'pNilSecurity' => $nilsecurity,
					  'pNilFidu' => FALSE,
					  'pNilCash' => $nilcash,
					  );
	   return $client->getAllPositions($parameters); 
	}
}

/**
 * Get balance data
 * @param string $soc Company
 * @param string $compte Account
 * @param string $datefin End date (YYYYMMDD)
 * @param boolean $value Date Date value (TRUE) or operation date (FALSE)
 * @return null|object
 */
function soap_getBalance($soc, $compte, $datefin, $value) {
    $user = getCurrentUser();
    if(!$user)
        return null;

    $client = soap_getSoapClient();
    $param = array(
        'pUser' => $user['username'],
        'pPassword' => $user['password'],
        'pLangue' => $user['language'],
        'pSoc' => $soc,
        'pCompte' => $compte,
        'pDateFin' => $datefin,
        'pValeur' => $value ? true : false
    );

    return $client->genBalance1($param);
}

/**
 * Build SOAP client
 * @return SoapClient
 */
function soap_getSoapClient() {
    return new SoapClient(SOAP_URL);
}

/**
 * Do response for AjaxRequest, support for JSONP
 * @param int $status The response status
 * @param mixed $body The content
 */
function responseAjax($status = 200, $body = '') {
    if(!is_numeric($status)) {
        $body = $status;
        $status = 200;
    }
    $callback = @$_GET['callback'];
    $codes = Array(
        100 => 'Continue',
        101 => 'Switching Protocols',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        306 => '(Unused)',
        307 => 'Temporary Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported'
    );

    $status_header = 'HTTP/1.1 ' . $status . ' ' . @$codes[$status];
    // set the status
    header($status_header);
    // set the content type
    if(!is_string($body)) {
        $content_type = "application/json";
        $body = json_encode($body);
    }
    else
        $content_type = 'text/html';
    header('Content-type: ' . $content_type);

    // send the body
    echo empty($callback) ? $body : "$callback($body)";
    exit;
}